package com.baseproject.volley;

import android.os.Handler;
import android.os.Looper;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * M 响应类型的泛型
 */

public class JSONHttpListener<M> implements IHttpListener {
    private Class<M> responseClass;

    /**
     * 回调调用的层的接口
     */
    private IDataListener<M> jsonListener;

    Handler handler = new Handler(Looper.getMainLooper());

    public JSONHttpListener(Class<M> responseClass, IDataListener<M> jsonListener) {
        this.responseClass = responseClass;
        this.jsonListener = jsonListener;
    }

    /**
     * 处理请求到的结果
     * @param inputStream
     */
    @Override
    public void onSuccess(InputStream inputStream) {
           String content = getContent(inputStream);

        //由于新浪云服务器暂未实名认证会返回多余的无效内容，因此过滤
        int index = content.indexOf("<script");
        String realContent = content.substring(0, index);

        //将json字符串类型转换为类类型
        final M response = JSON.parseObject(realContent, responseClass);
        handler.post(new Runnable() {
            @Override
            public void run() {
                jsonListener.onSuccess(response);
            }
        });
    }

    private String getContent(InputStream inputStream) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    @Override
    public void onError() {

    }
}
